package number_40;

import java.util.*;

public class Solution {
    private List<List<Integer>> res;
    public List<List<Integer>> combinationSum2(int[] candidates, int target) {
        res = new ArrayList<>();
        Arrays.sort(candidates);
        LinkedList<Integer> list = new LinkedList<>();
        backTrace(candidates, list, 0, target);
        return res;
    }

    private void backTrace(int[] candidates, LinkedList<Integer> list, int index, int target) {
        if (target == 0) {
            res.add(new ArrayList<>(list));
            return;
        }

        for (int i = index; i < candidates.length; i++) {
            if (target - candidates[i] >= 0) {
                if (i > index && candidates[i] == candidates[i - 1]) {
                    continue;
                }
                list.addLast(candidates[i]);
                backTrace(candidates, list, i + 1, target - candidates[i]);
                list.removeLast();
            }
        }
    }

    public static void main(String[] args) {
        new Solution().combinationSum2(new int[] {2,5,2,1,2}, 5);
    }
}
